# -*- coding: utf-8 -*-
# @Time: 2021/11/8 21:33
# @Author: jiuwu
# @Email: 2359196586@qq.com
# @File: tasks.py
# @Software: PyCharm
import logging
from celery_tasks.celery_main import app
from django.core.mail import send_mail
from promote.settings import EMAIL_HOST_USER

logger = logging.getLogger(__name__)  # 拿到日志器


@app.task(name="send_mail_task")  # 用装饰器变成celery的方法 传入一个任务名
def send_mail_task(email, username, password, classes_name):  # 这个方法是celery调用的
    """
    发送通知邮件
    :param email:
    :param username:
    :param password:
    :param classes_name:
    :return:
    """
    try:
        email_param = {
            'subject': '码趣教育-PROMOTE系统',  # 邮件标题
            'message': '',  # 文本信息
            'html_message':
                f"""
                <h2>欢迎加入码趣教育[{classes_name}]进行学习</h2>
                <h3>诚邀您使用码趣教育-PROMOTE系统</h3>
                <p>其中包含：题目知识点练习，升班考试测试，技术讨论社区等相关学习功能</p>
                <p>您的登录用户名为：<span style='color:#116bb7'>{username}</span></p>
                <p>您的登录初始密码为：<span style='color:#116bb7'>{password}</span>，登录后建议立即修改</p>
                <p><a href='#'>点击访问码趣教育-PROMOTE系统</a></p>
                """,
            'from_email': EMAIL_HOST_USER,  # 发件人地址，若省略，则使用DEFAULT_FROM_EMAIL中设置的值
            'recipient_list': [email],  # 收件人地址
        }
        res_email = send_mail(**email_param)
    except Exception as e:
        logger.error("验证码邮件发送[异常][ email: %s,message: %s]" % (email, e))
    else:
        if res_email != 1:
            logger.warning("验证码邮件发送[失败][ email: %s]" % email)
        else:
            logger.info("验证码邮件发送[正常][ email: %s,username: %s]" % (email, username))
